<?php

class ID implements Serializable {
	protected $value;

	public function Serialize(){ return serialize(array('value'=>$this->value)); }
	public function Unserialize($data){ $a = unserialize($data); $this->value=$a['value']; }

	public static function GetNextFor($tablename){ return Database::ExecuteGetNextIDFor($tablename); }

	public function __construct($value=null){
		if (is_null($value))
			$this->value = mt_rand(-0x7FFFFFF,0x7FFFFFFF);
		elseif (is_int($value))
			$this->value = $value;
		elseif ($value instanceof ID)
			$this->value = $value->value;
		elseif ($value instanceof DBItem)
			$this->value = $value->id->value;
		else {
			$s = strtoupper(trim(strval($value)));
			if (strlen($s)==8){
				$x = intval(substr($s,0,1),16);
				if ($x < 0x8)
					$this->value = intval($s,16);
				else { // Stupid PHP does not understand negative hex while scaning back
					$s = strval($x-0x8) . substr($s,1,7);
					$this->value = intval($s,16) ^ 0x7FFFFFFF + 1;
				}
			}
		}
	}

	public static function Random(){ return new ID(); }
	public static function Hash($value){ return new ID(substr(md5(strval($value)),0,8)); }

	public function AsInt(){
		return $this->value;
	}
	public function AsHex(){
		return sprintf('%08X',$this->value);
	}

	public function IsEqual($id) {
		if (is_null( $id)) return false;
		if ($id instanceof ID) return $this->value==$id->value;
		if (is_int($id)) return $this->value==$id;
		if ($id instanceof DBItem) return $this->IsEqual($id->id);
		return $this->AsHex()==strtoupper(trim(strval($value)));
	}

	public static function Compare($x1,$x2){
		if (is_null($x1)) return $is_null($x2) ? 0 : -1;
		if (is_null($x2)) return 1;
		return $x1->value - $x2->value;
	}

}



?>